package role

import (
	"SmartSearch/internal/models"
	"SmartSearch/internal/repositories"
	"SmartSearch/internal/responses"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
)

type Controller struct {
	roleRepository *repositories.RoleRepository
}

func NewRoleController() *Controller {
	return &Controller{
		roleRepository: &repositories.RoleRepository{},
	}
}

func (r *Controller) Add(c *gin.Context) {
	var role models.Role
	if err := c.BindJSON(&role); err != nil {
		c.JSON(http.StatusOK, responses.GenFailResult("参数解析错误"))
		return
	}
	if len(role.Name) < 1 {
		c.JSON(http.StatusOK, responses.GenFailResult("角色名称不能为空"))
		return
	}
	if _, err := r.roleRepository.FindByName(role.Name); err == nil {
		c.JSON(http.StatusOK, responses.GenFailResult("角色已经存在"))
		return
	}
	True := true
	role.Enable = &True
	role.CreatedDate = time.Now()
	if err := r.roleRepository.Add(&role); err != nil {
		c.JSON(http.StatusOK, responses.GenFailResult("角色创建失败"))
		return
	}
	c.JSON(http.StatusOK, responses.GenSuccessResult(nil))
}

func (r *Controller) Del(c *gin.Context) {
	var body struct {
		Id int64 `json:"id"`
	}
	if err := c.BindJSON(&body); err != nil {
		c.JSON(http.StatusOK, responses.GenFailResult("参数解析错误"))
		return
	}
	if _, err := r.roleRepository.FindById(body.Id); err != nil {
		c.JSON(http.StatusOK, responses.GenFailResult("角色不存在"))
		return
	}
	if err := r.roleRepository.Del(body.Id); err != nil {
		c.JSON(http.StatusOK, responses.GenFailResult("角色删除失败"))
		return
	}
	c.JSON(http.StatusOK, responses.GenSuccessResult(nil))
}

func (r *Controller) List(c *gin.Context) {
	name := c.Query("name")
	var enable *bool
	if s, err := strconv.ParseBool(c.Query("enable")); err == nil {
		enable = &s
	}
	current, _ := strconv.ParseInt(c.DefaultQuery("current", "0"), 10, 32)
	pageSize, _ := strconv.ParseInt(c.DefaultQuery("pageSize", "10"), 10, 32)
	list := r.roleRepository.GetList(name, enable, int32(current), int32(pageSize))
	c.JSON(http.StatusOK, responses.GenSuccessResult(list))
}

func (r *Controller) Update(c *gin.Context) {
	var body struct {
		Id     int64  `json:"id"`
		Name   string `json:"name"`
		Enable *bool  `json:"enable"`
	}
	if err := c.BindJSON(&body); err != nil {
		c.JSON(http.StatusOK, responses.GenFailResult("参数解析错误"))
		return
	}
	role, err := r.roleRepository.FindById(body.Id)
	if err != nil {
		c.JSON(http.StatusOK, responses.GenFailResult("角色不存在"))
		return
	}
	role.Name = body.Name
	role.Enable = body.Enable
	if err := r.roleRepository.Update(role); err != nil {
		c.JSON(http.StatusOK, responses.GenFailResult("角色删除失败"))
		return
	}
	c.JSON(http.StatusOK, responses.GenSuccessResult(nil))
}
